<template>
    <div class="chatPanelcontainer" v-if="chatList.length">
        <div class="panel-left">
            <div :class="item.name === chatModel.getCurrentChatfriend() && 'activeUser'" v-for="item in chatList"
                @click="checkChatFriend(item.name)" class="chat-user">
                <img class="img" :title="item.nickname" width="50" height="50" :src="Util.getImgUrl(item.avatar)">
            </div>
        </div>
        <!-- 聊天框主页面 -->
        <div class="panel-mian">
            <div class="message" ref="msgBox">
                <div v-for=" item in msgList">
                    <div :class="item.sender !== myName ? 'chatBox-l' : 'chatBox-r'">
                        <img class="chatAvatar" :src="getImgUrl(item.sender === myName)">
                        <div :class="item.sender !== myName ?
                            'chatContent-l' : 'chatContent-r'">
                            {{ item.content }}
                        </div>
                        <!-- <div class="createTime">
                            {{ getMsgTime(item.createdAt) }}
                        </div> -->
                    </div>
                </div>
            </div>
            <div class="input-box">
                <textarea class="textarea" :placeholder="placeholder" name="" id="" cols="60" rows="8" v-model="inputVal"
                    @keydown="e => keydownHandler(e)"></textarea>
                <div class="button">
                    <div class="close" @click="close">关闭(Esc)</div>
                    <div class="sendMsg" @click="sentMsg">发送(Enter)</div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import chatModel from '@/ChatMocel'
import { ChatMsgInfo, ChatInfo } from '@/Util/Constant'
import { getUserInfo, Util } from "@/Util";
import eventBus from '@/Util/EventBus'
import socket from '@/socket/UserChatSocket';
import { SocketEventType } from '@/share/commonType';
let chatList = ref<ChatInfo[]>([])
let msgList = ref<ChatMsgInfo[]>([])
let inputVal = ref('')
let userInfo = getUserInfo()
let myName = userInfo.username
let msgBox = ref()
const { close } = defineProps<{
    close: any
}>()
let placeholder = '开始聊天吧！*^▽^* \n按Enter发送，Shift+Enter换行'
onMounted(() => {
    updateChatList()
    updateMsgList()
    eventBus.on('updateChatList', updateChatList)
    eventBus.on('updateMsgList', updateMsgList)
    eventBus.on('updateScroller', updateScroller)
})
let updateMsgList = async () => {
    msgList.value = await chatModel.getChatMsg()
}
let updateChatList = () => {
    chatList.value = chatModel.getChatList()
}

let checkChatFriend = (friend: string) => {
    chatModel.setCurrentChatfriend(friend)
}
let keydownHandler = (e: any) => {
    if (e.shiftKey && e.key === 'Enter') return;
    if (e.keyCode == 13) {
        e.preventDefault(); // 阻止输入换行符
        sentMsg()
    } else if (e.keyCode == 27) {
        close()
    }
}

let getImgUrl = (isMe: boolean) => {
    if (isMe) {
        return Util.getImgUrl(userInfo.avatar)
    } else {
        let name = chatModel.getCurrentChatfriend()
        let avatar = chatList.value.find((item) => item.name == name)?.avatar as string
        return Util.getImgUrl(avatar)
    }
}
let getMsgTime = (time: string) => {
    return time;
}
let updateScroller = (updateNow?: boolean) => {
    let scroller = msgBox.value as HTMLDivElement
    if (scroller?.scrollHeight) {
        setTimeout(() => {
            scroller.scrollTop = scroller.scrollHeight
        }, updateNow ? 0 : 30)
    }
}
let sentMsg = async () => {
    let nowChatFriend = chatModel.getCurrentChatfriend()
    if (inputVal.value) {
        socket.emit({
            action: SocketEventType.ChatMessage,
            data: {
                sender: myName,
                receiver: nowChatFriend,
                content: inputVal.value,
                createdAt: new Date().getTime()
            }
        })
        await chatModel.addChatMsgForModel({ // 这个地方是异步的，所以要想updateChatList最新的数据，必须等这里异步任务做完
            sender: myName,
            content: inputVal.value,
            createdAt: new Date().getTime().toString()
        })
        updateMsgList()
        inputVal.value = ''
        updateScroller()
    }
}
</script>


<style scoped lang="less">
.chatPanelcontainer {
    width: 100%;
    height: 100%;
    display: flex;

    .panel-left {
        height: 100%;
        width: 70px;
        display: flex;
        align-items: center;
        flex-direction: column;
        border-right: 1px solid #545454;

        .activeUser {
            background-color: #9b9ea1;
        }

        .chat-user {
            width: 100%;
            height: 60px;
            padding: 5px 0;
            text-align: center;

            .img {
                border-radius: 50%;
            }
        }

    }

    .panel-mian {
        padding-top: 5px;
        height: 100%;
        flex: 1;
        display: flex;
        flex-direction: column;
        position: relative;

        .message {
            overflow-y: auto;
            overflow-x: hidden;
            margin-bottom: 140px;

            .chatBox-r {
                flex-direction: row-reverse;

                .createTime {
                    right: 24px;
                }
            }

            .chatBox-l {
                .createTime {
                    left: 25px;
                }
            }

            .chatBox-l,
            .chatBox-r {
                display: flex;
                width: 100%;
                margin-bottom: 12px;
                font-size: 13px;
                font-family: '微软雅黑', '宋体';
                position: relative;

                .createTime {
                    position: absolute;
                    transform: scale(.7);
                    bottom: -14px;
                    transition: .2s;
                    opacity: 0;
                }

                &:hover {
                    .createTime {
                        opacity: 1;
                    }
                }

                .chatContent-l {
                    background-color: #abcee5;
                }

                .chatContent-r {
                    background-color: #12b7f5;
                }

                .chatContent-l,
                .chatContent-r {
                    max-width: 200px;
                    padding: 5px 8px;
                    border-radius: 5px;
                    white-space: pre-line;
                    word-wrap: break-word; // 让过长的单词自动换行
                }

                .chatAvatar {
                    display: block;
                    width: 30px;
                    height: 30px;
                    border-radius: 50%;
                    margin: 0 8px;
                }
            }


        }

        .input-box {
            position: absolute;
            width: 100%;
            height: 140px;
            left: 0;
            bottom: 0;
            background-color: rgba(204, 210, 219, .5);

            .textarea {
                width: 100%;
                height: 70%;
                background-color: rgba(204, 210, 219, 0);
                outline: none;
                border: none;
                font-size: 16px;
                padding: 5px 5px;
                font-family: '微软雅黑';
                resize: none;
            }

            .button {
                display: flex;
                height: 20%;
                float: right;
                color: #000;
                align-items: center;
                font-size: 14px;
                user-select: none;

                .sendMsg,
                .close {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    margin-right: 10px;
                    border-radius: 3px;
                    cursor: pointer;
                }

                .close {
                    width: 80px;
                    height: 100%;
                    background-color: #d2d4da;

                    &:hover {
                        background-color: #efeff0;
                    }
                }

                .sendMsg {
                    width: 95px;
                    height: 100%;
                    color: #fff;
                    background-color: #4e6487;

                    &:hover {
                        background-color: #8797b2;
                    }
                }
            }
        }
    }
}
</style>
